package com.jmz.apt.api.service.user;

import com.jmz.apt.api.dao.AdminDao;
import com.jmz.apt.api.dao.AdminRoleDao;
import com.jmz.apt.api.dao.AdminUserRoleDao;
import com.jmz.apt.api.entity.dbEntity.JmzAdminRole;
import com.jmz.apt.api.entity.dbEntity.JmzAdminUser;
import com.jmz.apt.api.entity.dbEntity.JmzAdminUserRoles;
import com.jmz.apt.api.enums.ResponseCode;
import com.jmz.apt.api.exception.BusinessException;
import com.jmz.apt.api.exception.MyDataAccessException;
import com.jmz.apt.api.message.request.Condition;
import com.jmz.apt.api.message.request.Query;
import com.jmz.apt.api.message.request.RequestMessage;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by fanglexue on 2019/10/24.
 */

@Component
public class AdminUser {

    @Autowired AdminDao adminDao;

    @Autowired
    AdminUserRole adminUserRole;

    public List<JmzAdminUser> findAllAdminUsers(RequestMessage requestMessage){
        List<Condition> condition = requestMessage.getMessage().getBody().getQuery().getCondition();
        Query query = requestMessage.getMessage().getBody().getQuery();
        List<JmzAdminUser> jmzAdminUsers = adminDao.findAdmin("*",condition,query);
        return jmzAdminUsers;
    }

    public Integer saveAdminUser(JmzAdminUser adminUser) throws DataAccessException{
        JmzAdminUser cond = new JmzAdminUser();
        cond.setName(adminUser.getName());
        cond.setEmail(adminUser.getEmail());
        cond.setMobile(adminUser.getMobile());
        JmzAdminUser dbUser = adminDao.findRepeatOne(cond);
        if(dbUser == null) {
            Integer adminId = adminDao.saveAdmin(adminUser);
            return adminId;
        }
        return dbUser.getId();
    }

    public Boolean updateAdminUser(JmzAdminUser adminUser) throws DataAccessException{
        JmzAdminUser cond = new JmzAdminUser();
        if(null == adminUser.getId()){
            throw new BusinessException(ResponseCode.DB_LOSE_PARM.getCode(),
                    ResponseCode.DB_LOSE_PARM.getDesc());
        }
        cond.setId(adminUser.getId());
        JmzAdminUser dbUser = adminDao.findAdminOne(cond);
        if(dbUser == null) {
            return false;
        }
        adminDao.updateAdmin(adminUser);
        return true;
    }

    public Boolean deleteAdminUser(JmzAdminUser adminUser) throws DataAccessException{
        JmzAdminUser cond = new JmzAdminUser();
        if(null == adminUser.getId()){
            throw new BusinessException(ResponseCode.DB_LOSE_PARM.getCode(),
                    ResponseCode.DB_LOSE_PARM.getDesc());
        }
        cond.setId(adminUser.getId());
        adminDao.delete(adminUser);
        return true;
    }


    public JmzAdminUser getAdUserInfo(Integer adminId){
        return adminDao.findAdminJoinRoles(adminId);
    }
}
